import tkinter as tk
from tkinter import filedialog
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


def upload_file():
    # 打开文件选择对话框
    filename = filedialog.askopenfilename(initialdir='/', title='选择成绩文件',
                                          filetypes=[('Excel files', '*.xlsx *.xls')])

    # 如果用户选择了文件，则读取数据并进行相关分析
    if filename:
        try:
            # 读取 Excel 文件
            df = pd.read_excel(filename)

            # 计算每个数值型列之间的相关系数
            corr_mtx = df.select_dtypes(include='number').corr()

            # 可视化相关矩阵
            plt.rcParams['font.family'] = ['STSong']
            plt.subplots(figsize=(10, 8))
            plt.imshow(corr_mtx, cmap='coolwarm', interpolation='nearest')
            plt.colorbar()
            tick_marks = [i for i in range(len(corr_mtx.columns))]
            plt.xticks(tick_marks, corr_mtx.columns, rotation=45)
            plt.yticks(tick_marks, corr_mtx.columns)
            plt.title('Pearson Correlation Matrix')
            plt.show()

            # 将相关矩阵保存到 Excel 文件
            # corr_mtx.to_excel('pearson_correlation_test001.xlsx', index=None)

        except Exception as e:
            # 提示用户出错信息
            tk.messagebox.showerror(title='错误', message=e)


# 创建主窗口
root = tk.Tk()
root.title('成绩文件分析')

# 创建按钮
button = tk.Button(root, text='上传文件', command=upload_file)
button.pack()

# 运行主程序
root.mainloop()
